JavaScript Essentials by Smashing Magazine
Author: Smashing Magazine , Date: March 24, 2014
, Views: 368
You may have noticed that I didn’t include empty arrays in the list of falsies above. Empty arrays are curious things: they actually evaluate to truthy but, when compared against a boolean, behave like a falsy. Confused yet? With good cause. Another example perhaps?
var someVar = []; //empty array
alert(someVar == false); //evaluates true
if (someVar) alert('hello'); //alert runs, so someVar evaluates to true
To avoid coercion, you can use the value and type comparison operator, ===, (as opposed to ==, which compares only by value). So:
var someVar = 0;
alert(someVar == false); //evaluates true – zero is a falsy
alert(someVar === false); //evaluates false – zero is a number, not a boolean
Copyright Disclaimer:
This site does not store any files on its server. We only index and link
to content provided by other sites. Please contact the content providers
to delete copyright contents if any and email us, we'll remove relevant
links or contents immediately.